package net.kleinhenz.questor.ui;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.kleinhenz.questor.Questor;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

public class WebPlayerView extends WebView
{
	private Map<String, String> replacementMap = new HashMap<String, String>();
	private String playerHTML;
	private String playerMimeType;
	private String playerEncoding;
	
	public WebPlayerView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}

	public WebPlayerView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	public WebPlayerView(Context context)
	{
		super(context);	
	}

	public void reloadPlayerData()
	{
		if (playerHTML==null)
			loadPlayerHTML();
		loadData(playerHTML, playerMimeType, playerEncoding);
	}

	public void loadPlayerHTML()
	{
		if (Questor.getCurrentGame().getCurrentQSR()!=null)
			try
			{
				BufferedReader reader = new BufferedReader(new FileReader(Questor.getCurrentGame().getCurrentQSR().getFile("/player.html")));
		
				StringBuffer html = new StringBuffer();
				int data = -1;
				while ((data=reader.read())!=-1)
					html.append((char)data);
				reader.close();	
		
				playerHTML = html.toString();
				playerMimeType = "text/html";
				playerEncoding = "UTF-8";
				reloadPlayerData();
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
	}
	
	public void setPlayerHTML(String html, String mimeType, String encoding)
	{
		playerHTML = html;
		playerMimeType = mimeType;
		playerEncoding = encoding;
	}
	
	public void setPlayerValue(String key, String value)
	{
		replacementMap.put(key, value);
		reloadPlayerData();
	}

	public void setPlayerValue(String key, int value)
	{
		setPlayerValue(key, "" + value);
	}
	
	public void setPlayerValue(String key, double value)
	{
		setPlayerValue(key, "" + value);
	}

	private String replaceData(Map<String, String> replacementMap, String data)
	{
		for (Map.Entry<String, String> entry : replacementMap.entrySet())
		{
			data.replaceAll(entry.getKey(), entry.getValue());
		}
		return data;
	}

	@Override
	public void loadData(String data, String mimeType, String encoding)
	{
		StringBuffer buf = new StringBuffer();
		buf.append("<xhtml><head><style>");
		buf.append("body{font-family:serif;font-size:16px}");
		buf.append("</style></head><body>");
		buf.append(replaceData(replacementMap, data));
		buf.append("<b>Hallo</b> Welt</body></xhtml>");

		super.loadData(buf.toString(), mimeType, encoding);
	}
}
